package com.heima.kafka.sample;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName KafkaStreamQuickStart
 * @Description 流式处理
 * @Author kiku
 * @Date 2024/9/2 16:07
 * @Version 1.0
 */
public class KafkaStreamQuickStart {
    public static void main(String[] args) {

        //kafka的配置信息
        Properties properties = new Properties();
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-quickstart");
        //stream构建器
        StreamsBuilder streamsBuilder = new StreamsBuilder();


        //流式计算
        streamsProcessor(streamsBuilder);
        //创建kafka的stream对象

        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(), properties);
        //开启流式计算
        kafkaStreams.start();
    }

    /**
     * 流式计算
     *
     * @param streamsBuilder
     */
    private static void streamsProcessor(StreamsBuilder streamsBuilder) {
        //创建kstream对象并且指定从哪个topic接收消息
        KStream<String, String> kStream = streamsBuilder.stream("itcast-topic-input");
        kStream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    @Override
                    public Iterable<String> apply(String value) {
                        String[] split = value.split(" ");
                        List<String> list = Arrays.asList(split);
                        return list;
                    }
                }).groupBy((key, value) -> value).windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //统计单词的个数
                .count().toStream()
                .map((key, value) -> {
                    System.out.println("key" + key + ",value" + value);
                    return new KeyValue<>(key.key().toString(), value.toString());

                }).to("itcast-topic-out");
    }
}
